package com.baizhi.controller;

import com.baizhi.common.Constant;
import com.baizhi.entity.Student;
import com.baizhi.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("upload")
    @ResponseBody
    public Map upload(MultipartFile file){
        //1、接收文件   使用的是方法形参MultipartFile file
        //2、利用UUID给上传后的文件重写命名  file.getOriginalFilename()这个是获取上传文件的原文件名
        String newFileName = UUID.randomUUID().toString()+file.getOriginalFilename();
        //3、将图片文件上传到虚拟目录
        try {
            file.transferTo(new File(Constant.IMG_LOCATION,newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4、将上传后的文件名响应给浏览器  隐藏在form表单内和其它数据一起提交
        Map map = new HashMap();
        map.put("flag",newFileName);
        return map;
    }

    @RequestMapping("add")
    @ResponseBody
    public Map add(Student student){
        System.out.println("添加收参"+student);
        Map map = new HashMap();
        try {
            studentService.insert(student);
            map.put("flag",true);
        } catch (Exception e) {
            map.put("flag",false);
        }
        return map;
    }
    @RequestMapping("delete")
    @ResponseBody
    public Map delete(int id){
        Map map = new HashMap();
        try {
            studentService.delete(id);
            map.put("flag",true);
        } catch (Exception e) {
            map.put("flag",false);
        }
        return map;
    }
    @RequestMapping("update")
    @ResponseBody
    public Map update(Student student){
        System.out.println("修改收参"+student);
        Map map = new HashMap();
        try {
            studentService.update(student);
            map.put("flag",true);
        } catch (Exception e) {
            map.put("flag",false);
        }
        return map;
    }
    @RequestMapping("getOne")
    @ResponseBody
    public Student getOne(int id){
        Student student = studentService.selectById(id);
        return student;
    }
    @RequestMapping("select")
    @ResponseBody
    public Map select(int page,int limit){
        Map map = new HashMap();
        PageInfo<Student> pageInfo = studentService.select(page, limit);
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map;
    }
}
